package org.onionframework.persistence.dao.functions.date;

import org.onionframework.persistence.dao.functions.DateFormatFunction;

public abstract class AbstractDateFormatFunction implements DateFormatFunction {

	protected static final String[] DATABASE_PATTERNS = {
		null,
		"yyyy","MM","dd",null,"hh","mm","ss",
		null,null,null,null,null,null,null,
		"hh"
	};
	
	@Override
	public String toSQL(String column, String pattern) {
		StringBuilder sb = new StringBuilder();
		
		sb.append(this.getFunctionName())
			.append('(').append(column).append(",\'")
			.append(this.getPattern(pattern)).append("')");
		
		return sb.toString();
	}

	protected String getPattern(String pattern) {
		StringBuilder sb = new StringBuilder();
		
		char[] compiledPattern = new DatePartternUtils().compile(pattern);
		
		String[] databasePatterns = this.getDatabasePatterns();
		
		//循环格式化字符串的编译结果，拼接数据库的格式化字符串
		//基本复制于SimpleDateFormat
		for (int i = 0; i < compiledPattern.length; i++) {
			int tag = compiledPattern[i] >>> 8;
			int count = compiledPattern[i] & 0xff;
			if (count == 255) {
				count = compiledPattern[i++] << 16;
				count |= compiledPattern[i++];
			}
			
			if(tag != 100 && tag != 101)
				sb.append(databasePatterns[tag]);
			else if(tag == 100)
				sb.append((char)count);
			else{
				char[] chars = new char[count];
				System.arraycopy(compiledPattern, i+1, chars, 0, count);
				sb.append(new String(chars));
				i = i + count;
			}
		}
		
		return sb.toString();
	}

	protected String[] getDatabasePatterns() {
		return DATABASE_PATTERNS;
	}

	protected abstract Object getFunctionName();

}
